import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../providers/music_provider.dart';
import 'music_player_page.dart';
import '../utils/image_cache_service.dart';

class NotesPage extends StatefulWidget {
  const NotesPage({Key? key}) : super(key: key);

  @override
  State<NotesPage> createState() => _NotesPageState();
}

class _NotesPageState extends State<NotesPage> with TickerProviderStateMixin {
  final ImageCacheService _imageCacheService = ImageCacheService();
  
  // 音乐封面旋转动画控制器
  late AnimationController _rotationController;
  late Animation<double> _rotationAnimation;

  @override
  void initState() {
    super.initState();
    
    // 初始化旋转动画
    _rotationController = AnimationController(
      duration: const Duration(seconds: 10), // 10秒旋转一圈
      vsync: this,
    );
    
    _rotationAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(_rotationController);
  }

  @override
  void dispose() {
    _rotationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFFFFFF), // paint_7:3 - white background
      body: SafeArea(
        child: Column(
          children: [
            // 顶部导航栏
            _buildTopNavigationBar(),
            // 笔记内容区域（左右分栏）
            Expanded(child: _buildNotesContent()),
            // 音乐播放条 - 只在有播放音乐时显示
            Consumer<MusicProvider>(
              builder: (context, musicProvider, child) {
                if (musicProvider.currentSong == null) {
                  return const SizedBox.shrink(); // 没有音乐时不显示
                }
                return _buildMusicPlayBar(musicProvider);
              },
            ),
          ],
        ),
      ),
    );
  }

  // 顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      width: double.infinity,
      height: 44,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: Row(
        children: [
          // 播放列表图标
          Container(
            width: 32,
            height: 32,
            alignment: Alignment.center,
            child: Icon(
              Icons.playlist_play,
              color: const Color(0xFF000000), // paint_7:190
              size: 22,
            ),
          ),
          
          const Spacer(),
          
          // 关注和推荐按钮容器
          Container(
            height: 32,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 关注按钮
                Container(
                  height: 32,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  alignment: Alignment.center,
                  child: Text(
                    '关注',
                    style: TextStyle(
                      color: const Color(0xFF3D3D3D), // paint_7:00
                      fontSize: 15,
                      fontFamily: 'Source Han Sans',
                      fontWeight: FontWeight.w600,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
                
                const SizedBox(width: 16),
                
                // 推荐按钮（当前选中）
                Container(
                  height: 32,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        color: const Color(0xFFF73E3B),
                        width: 2,
                      ),
                    ),
                  ),
                  child: Text(
                    '推荐',
                    style: TextStyle(
                      color: const Color(0xFFF73E3B), // paint_7:2025 - NetEase red
                      fontSize: 15,
                      fontFamily: 'Source Han Sans',
                      fontWeight: FontWeight.w600,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
              ],
            ),
          ),
          
          const Spacer(),
          
          // 右侧图标组
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 搜索图标
              Container(
                width: 32,
                height: 32,
                alignment: Alignment.center,
                child: Icon(
                  Icons.search,
                  color: const Color(0xFFA6A6A6), // paint_7:1120
                  size: 22,
                ),
              ),
              
              const SizedBox(width: 12),
              
              // 添加图标
              Container(
                width: 32,
                height: 32,
                alignment: Alignment.center,
                child: Icon(
                  Icons.add_circle,
                  color: const Color(0xFFF73E3B), // paint_7:1628
                  size: 22,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 笔记内容区域
  Widget _buildNotesContent() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 1),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 左侧笔记
          Expanded(
            child: _buildLeftNotes(),
          ),
          const SizedBox(width: 3),
          // 右侧笔记
          Expanded(
            child: _buildRightNotes(),
          ),
        ],
      ),
    );
  }

  // 左侧笔记
  Widget _buildLeftNotes() {
    return SingleChildScrollView(
      child: Column(
        children: [
          const SizedBox(height: 15),
          _buildNoteCard(
            imageUrl: 'img/笔记页/封面/笔记1.jpeg',
            text: '想念你们了',
            avatarUrl: 'img/笔记页/头像/头像1.PNG',
            username: 'Anna',
            likes: '45',
            height: 232,
          ),
          const SizedBox(height: 9),
          _buildNoteCard(
            imageUrl: 'img/笔记页/封面/笔记2.jpeg',
            text: '快乐，hay翻天！',
            avatarUrl: 'img/笔记页/头像/头像2.PNG',
            username: 'Yanami',
            likes: '167',
            height: 232,
          ),
          const SizedBox(height: 9),
          _buildNoteCard(
            imageUrl: 'img/笔记页/封面/笔记3.jpeg',
            text: '生活如此美好',
            avatarUrl: 'img/笔记页/头像/头像3.PNG',
            username: 'Mikko',
            likes: '89',
            height: 232,
          ),
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  // 右侧笔记
  Widget _buildRightNotes() {
    return SingleChildScrollView(
      child: Column(
        children: [
          const SizedBox(height: 13),
          _buildNoteCard(
            imageUrl: 'img/笔记页/封面/笔记4.jpeg',
            text: '不如让灯光再暗点～',
            avatarUrl: 'img/笔记页/头像/头像4.PNG',
            username: 'Takina',
            likes: '98',
            height: 317,
          ),
          const SizedBox(height: 10),
          _buildNoteCard(
            imageUrl: 'img/笔记页/封面/笔记5.jpeg',
            text: '音乐是灵魂的语言',
            avatarUrl: 'img/笔记页/头像/头像5.PNG',
            username: 'Luna',
            likes: '156',
            height: 317,
          ),
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  // 笔记卡片
  Widget _buildNoteCard({
    required String imageUrl,
    required String text,
    required String avatarUrl,
    required String username,
    required String likes,
    required double height,
  }) {
    double imageHeight = height == 232 ? 154 : 239;
    return Container(
      width: 183,
      height: height,
      margin: const EdgeInsets.symmetric(horizontal: 5),
      child: Column(
        children: [
          // 分享图片
          Container(
            width: 183,
            height: imageHeight,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              image: DecorationImage(
                image: AssetImage(imageUrl),
                fit: BoxFit.cover,
              ),
            ),
          ),
          // 文本+人物信息
          Container(
            width: 183,
            height: 78,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 文字内容
                Padding(
                  padding: const EdgeInsets.only(left: 9, top: 11),
                  child: Text(
                    text,
                    style: TextStyle(
                      color: const Color(0xFF3D3D3D), // paint_7:00
                      fontSize: 14,
                      fontFamily: 'Source Han Sans',
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                const SizedBox(height: 8),
                // 用户信息行
                Padding(
                  padding: const EdgeInsets.only(left: 9, right: 9),
                  child: Row(
                    children: [
                      // 头像
                      Container(
                        width: 30,
                        height: 30,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          image: DecorationImage(
                            image: AssetImage(avatarUrl),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      const SizedBox(width: 10),
                      // 用户名
                      Text(
                        username,
                        style: TextStyle(
                          color: const Color(0xFFB9B9B9), // paint_7:1860
                          fontSize: 12,
                          fontFamily: 'Source Han Sans',
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const Spacer(),
                      // 点赞图标
                      Container(
                        width: 16,
                        height: 16,
                        child: Icon(
                          Icons.thumb_up,
                          color: const Color(0xFFA6A6A6), // paint_7:0979
                          size: 12,
                        ),
                      ),
                      const SizedBox(width: 5),
                      // 点赞数
                      Text(
                        likes,
                        style: TextStyle(
                          color: const Color(0xFFB9B9B9), // paint_7:1860
                          fontSize: 12,
                          fontFamily: 'Source Han Sans',
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 音乐播放条
  Widget _buildMusicPlayBar(MusicProvider musicProvider) {
    final song = musicProvider.currentSong;
    
    // 根据播放状态控制旋转动画
    if (musicProvider.isPlaying) {
      _rotationController.repeat();
    } else {
      _rotationController.stop();
    }
    
    return Container(
      width: double.infinity,
      height: 55,
      decoration: BoxDecoration(
        color: const Color(0xFFFFFFFF), // paint_7:3
        border: Border(
          top: BorderSide(
            color: Colors.grey[200]!,
            width: 0.5,
          ),
        ),
      ),
      child: Row(
        children: [
          // 左侧可点击区域（封面和歌曲信息）
          Expanded(
            child: GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const MusicPlayerPage(),
                  ),
                );
              },
              child: Row(
                children: [
                  const SizedBox(width: 17),
                  
                  // 音乐封面 - 使用旋转动画和图片缓存
                  Container(
                    width: 45,
                    height: 45,
                    decoration: const BoxDecoration(
                      color: Colors.black,
                      shape: BoxShape.circle,
                    ),
                    child: RotationTransition(
                      turns: _rotationAnimation,
                      child: Container(
                        margin: const EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          color: Colors.grey[300],
                          shape: BoxShape.circle,
                          image: _getAlbumArtDecoration(song?.albumArtUri),
                        ),
                        child: song?.albumArtUri == null || song!.albumArtUri!.isEmpty
                            ? const Icon(
                                Icons.music_note,
                                color: Colors.grey,
                                size: 20,
                              )
                            : null,
                      ),
                    ),
                  ),
                  
                  const SizedBox(width: 12),
                  // 歌曲标题
                  Expanded(
                    child: Text(
                      song?.name ?? 'SUPERPOWER',
                      style: TextStyle(
                        color: const Color(0xFF3D3D3D), // paint_7:00
                        fontSize: 16,
                        fontFamily: 'Source Han Sans',
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
          ),
          
          // 播放按钮（不跳转页面）
          GestureDetector(
            onTap: () {
              if (song != null) {
                musicProvider.togglePlayPause();
              }
            },
            child: Container(
              width: 36,
              height: 36,
              margin: const EdgeInsets.only(right: 8),
              child: Icon(
                musicProvider.isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled,
                color: Colors.black54,
                size: 36,
              ),
            ),
          ),
          
          // 菜单按钮（跳转到音乐播放页）
          GestureDetector(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const MusicPlayerPage(),
                ),
              );
            },
            child: Container(
              width: 36,
              height: 36,
              margin: const EdgeInsets.only(right: 12),
              child: const Icon(
                Icons.menu,
                color: Colors.black54,
                size: 24,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 获取专辑封面装饰，使用缓存避免闪烁
  DecorationImage? _getAlbumArtDecoration(String? albumArtUri) {
    final imageProvider = _imageCacheService.getImageProvider(albumArtUri);
    if (imageProvider != null) {
      return DecorationImage(
        image: imageProvider,
        fit: BoxFit.cover,
      );
    }
    return null;
  }
} 